//
//  mm_partModifyViewController.m
//  HondaPro_2
//
//  Created by Eric on 13-7-20.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "mm_partModifyViewController.h"
#import "MyAFNetWorkManager.h"
#import "SVProgressHUD.h"

@interface mm_partModifyViewController ()


@property (weak, nonatomic) IBOutlet UIButton *chargeDiffBtn;
/** 收费区分列表 */
@property(nonatomic,strong)NSMutableDictionary *chargeDiff;
@property(nonatomic,strong)NSMutableArray *chargeDiffKeys;
@property(nonatomic,strong)NSMutableDictionary *chargeDiffValKey;

/** 维修项目 */
@property(nonatomic,strong)NSMutableArray *projectTypeNames;
@property(nonatomic,strong)NSMutableDictionary *projectTypeNameDic;
@property(nonatomic,strong)NSMutableDictionary *projectTypeCodeDic;
@property(nonatomic,strong)NSMutableArray *chargeTypeCodes;//维修项目对应的收费区分

@property(nonatomic,weak) IBOutlet UIButton *projectTypeBtn;

/** 销售价格 */
@property(nonatomic,assign)double salesPrice;
/** 索赔价格 */
@property(nonatomic,assign)double claimPrice;
//维修分类
@property (weak, nonatomic) IBOutlet UIButton *repairTypeBtn;
@property(nonatomic,strong)NSMutableArray *repairTypeNames;
@property(nonatomic,strong)NSMutableDictionary *repairTypeDic;
@property(nonatomic,strong)NSMutableDictionary *repairTypeCodeDic;
@end

@implementation mm_partModifyViewController
-(NSMutableArray *)repairTypeNames{
    if (_repairTypeNames == nil) {
        _repairTypeNames= [NSMutableArray array];
        _repairTypeDic = [NSMutableDictionary dictionary];
        _repairTypeCodeDic=[NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_REPAIR_TYPE_ITEM"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_repairTypeNames addObject:name];
            [_repairTypeDic setObject:val forKey:name];
            [_repairTypeCodeDic setObject:name forKey:val];
        }
    }
    return _repairTypeNames;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.frame = CGRectMake(0, 0, 500, 600);
    
    //初始化数据
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSDictionary *dicTmp = modelIns.partList[modelIns.nRowForPartList];
    self.partCodeIns.text = dicTmp[@"PART_NO"];
    self.partNameIns.text = dicTmp[@"PART_NAME"];
    self.priceTxt.text = [NSString stringWithFormat:@"%.2f",[dicTmp[@"PART_SALES_PRICE"] doubleValue]];
    self.quantityTxt.text = [NSString stringWithFormat:@"%d",[dicTmp[@"PART_QUANTITY"] integerValue]];
    self.amountTxt.text = [NSString stringWithFormat:@"%.2f",[dicTmp[@"PART_SALES_AMOUNT"] doubleValue]];
    [self chargeDiffKeys];
    [self.chargeDiffBtn setTitle:self.chargeDiffValKey[dicTmp[@"CHARGE_PARTITION_CODE"]] forState:UIControlStateNormal];
    [self projectTypeNames];
    [self.projectTypeBtn setTitle:self.projectTypeCodeDic[dicTmp[@"LABOUR_CODE"]] forState:UIControlStateNormal];
    
    [self repairTypeNames];
    [self.repairTypeBtn setTitle:self.repairTypeCodeDic[dicTmp[@"REPAIR_TYPE_CODE"]] forState:UIControlStateNormal];
    [self registerNotificationForKeyBoard];
    
    //查找配件相关信息
    [self searchPartInfo:dicTmp[@"ITEM_ID"]];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

/** 查找配件相关信息 */
-(void)searchPartInfo:(NSString *)itemId{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"ITEM_ID"] = itemId;
    [SVProgressHUD showWithStatus:@"请等待...."];
    [MyAFNetWorkManager postWithParam:param andAction:@"QUERY_SALESANDCLAIM_PRICE_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        [SVProgressHUD dismiss];
        if (error) {
            NSLog(@"查询索赔、销售价格出错");
        }else{
            NSDictionary *result = obj[@"TM_PART_STOCK_PRICE"][0];
            self.claimPrice = [result[@"CLAIM_PRICE"]doubleValue];
            self.salesPrice = [result[@"SALES_PRICE"]doubleValue];
        }
    
    }];
}

#pragma mark - 保存数据的方法
-(BOOL)saveData
{
    NSString *msg = [self getErrorMsg];
    if (msg) {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        return false;
    }
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    NSMutableDictionary *dicTmp = modelIns.partList[modelIns.nRowForPartList];
    NSString *chargeDiffVal = self.chargeDiff[self.chargeDiffBtn.titleLabel.text];
    NSString *projectTypeCode = self.projectTypeNameDic[self.projectTypeBtn.titleLabel.text];
    if (!chargeDiffVal) {
        chargeDiffVal = @"";
    }
    double price = [self.priceTxt.text doubleValue];
    int count = [self.quantityTxt.text integerValue];
    double amout = [self.amountTxt.text doubleValue];
    [dicTmp setObject:@(self.discount) forKey:@"DISCOUNT"];
    dicTmp[@"LABOUR_CODE"] = projectTypeCode;
    dicTmp[@"LABOUR_NAME"] = self.projectTypeBtn.titleLabel.text;
    [dicTmp setObject:chargeDiffVal forKey:@"CHARGE_PARTITION_CODE"];//收费区分
    [dicTmp setObject:@(price) forKey:@"PART_SALES_PRICE"];//销售价格
    [dicTmp setObject:@(count) forKey:@"PART_QUANTITY"];//数量
    [dicTmp setObject:@(amout) forKey:@"PART_SALES_AMOUNT"];//金额
    NSString*itemID=[NSString stringWithFormat:@"%zd",[dicTmp[@"ITEM_ID"] integerValue]];
    if (![itemID isEqualToString:@"0"]) {
        [dicTmp setObject:@"U" forKey:@"STATUS"];
    }else{
        [dicTmp setObject:@"A" forKey:@"STATUS"];
    }
    [dicTmp setObject:self.repairTypeDic[self.repairTypeBtn.currentTitle] forKey:@"REPAIR_TYPE_CODE"];//维修分类
    return true;
}

-(NSString *)getErrorMsg{
    NSString *msg = nil;
    if (self.priceTxt.text.length<=0){
        msg = @"请输入销售价格！";
    }else if (self.quantityTxt.text.length<=0){
        msg = @"请输入数量！";
    }else if (self.projectTypeBtn.currentTitle.length<=0){
        msg = @"请选择维修项目";
    }else if (self.chargeDiffBtn.currentTitle.length<=0){
        msg = @"收费区分不能为空";
    }else if (self.repairTypeBtn.currentTitle.length<=0){
        msg = @"请选择维修分类";
    }
    return msg;
}

#pragma mark - 键盘托起屏幕的代理方法

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // When the user presses return, take focus away from the text field so that the keyboard is dismissed.
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.superview.frame.size.width, self.view.superview.frame.size.height);
    self.view.superview.frame = rect;
    [UIView commitAnimations];
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    int offset = 150;//键盘高度350
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.superview.frame.size.width;
    float height = self.view.superview.frame.size.height;
    if(offset > 0)
    {
        CGRect rect = CGRectMake(0.0f, -offset,width,height);
        self.view.superview.frame = rect;
    }
    [UIView commitAnimations];
}

//注册键盘消息
-(void)registerNotificationForKeyBoard
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setViewNormal) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

-(void)textFieldValueChange:(NSNotification *)note{
    [self computeAmount];
}

-(void)computeAmount{
    double count = [self.quantityTxt.text doubleValue];
    double price = [self.priceTxt.text doubleValue];
    self.amountTxt.text = [NSString stringWithFormat:@"%.2f",count * price];
}

-(void)setPriceWithChargeDiffCode:(NSString *)code{
    //如果收费区分是首保、保修、市场活动、PDI、配件索赔，那么配件销售价就去索赔价，反之去销售价
    double price = 0;
    if ([code isEqualToString:@"S002"]||[code isEqualToString:@"S004"]||[code isEqualToString:@"S008"]||[code isEqualToString:@"S009"]||[code isEqualToString:@"S010"]) {
        price = self.claimPrice;
    }else{
        price = self.salesPrice;
    }
    self.priceTxt.text = [NSString stringWithFormat:@"%.2f",price];
}

//视图回归正常状态
-(void)setViewNormal
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.superview.frame.size.width, self.view.superview.frame.size.height);
    self.view.superview.frame = rect;
    [UIView commitAnimations];
}



#pragma mark -懒加载
/** 收费区分 */
-(NSMutableArray *)chargeDiffKeys{
    if (_chargeDiffKeys == nil) {
        _chargeDiffKeys= [NSMutableArray array];
        _chargeDiff = [NSMutableDictionary dictionary];
        _chargeDiffValKey = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_CHARGE_PARTITION"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_chargeDiffKeys addObject:name];
            [_chargeDiff setObject:val forKey:name];
            [_chargeDiffValKey setObject:name forKey:val];
        }
    }
    return _chargeDiffKeys;
}

/** 维修项目 */
-(NSMutableArray *)projectTypeNames{
    if (_projectTypeNames == nil) {
        NSMutableArray *names = [NSMutableArray array];
        _chargeTypeCodes = [NSMutableArray array];
        _projectTypeNameDic = [NSMutableDictionary dictionary];
        _projectTypeCodeDic = [NSMutableDictionary dictionary];
        MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
        NSArray *arrRepairItemList = modelIns.repairProjects;
        NSString *projetName = nil;
        NSString *code = nil;
        for (NSDictionary *dic in arrRepairItemList) {
            projetName = dic[@"LABOUR_NAME"];
            code = dic[@"LABOUR_CODE"];
            if (projetName.length>0) {
                [names addObject:projetName];
                _projectTypeNameDic[projetName] = code;
                _projectTypeCodeDic[code] = projetName;
                if (dic[@"CHARGE_PARTITION_CODE"]) {
                    [_chargeTypeCodes addObject:dic[@"CHARGE_PARTITION_CODE"]];
                }else{
                    [_chargeTypeCodes addObject:@""];
                }
            }
        }
        _projectTypeNames = names;
    }
    
    return _projectTypeNames;
}

-(NSMutableDictionary *)readershuDICimform
{
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *str=[path stringByAppendingPathComponent:@"Dic.text"];
    dic=[NSMutableDictionary dictionaryWithContentsOfFile:str];
    //nslog(@"%@",dic);
    return dic;
}

#pragma mark - 创建下拉菜单方法
-(void)createThePopViewControl:(UIButton *)sender
{
    if (!contentCon)
    {
        contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
    }
    
    contentCon.delegate = self;
    contentCon.btnSender=sender;
    
    popCon = [[UIPopoverController alloc] initWithContentViewController:contentCon];
    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:222 alpha:0.9]];
    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
    [DDPopoverBackgroundView setArrowHeight:15.0];
    [DDPopoverBackgroundView setContentInset:1.0];
    
    [popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
    [popCon setPopoverContentSize:CGSizeMake(sender.frame.size.width, 280)];
    
    [popCon presentPopoverFromRect:CGRectMake(40, 15, 70, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

//弹出的回调方法
-(void)selectDelegate:(NSInteger)row btn:(UIButton *)btn
{
    NSString *text = nil;
    if (btn == self.projectTypeBtn) {
        text = self.projectTypeNames[row];
        NSString *code = self.chargeTypeCodes[row];//获取收费区分代码
        [self chargeDiffKeys];
        NSString *chargeTypeName = self.chargeDiffValKey[code];
        [self.chargeDiffBtn setTitle:chargeTypeName forState:UIControlStateNormal];
        [self setPriceWithChargeDiffCode:code];
        [self computeAmount];
    }else if (btn == self.chargeDiffBtn){
        text = self.chargeDiffKeys[row];
    }else if (btn == self.repairTypeBtn){
        text = self.repairTypeNames[row];
    }
    [btn setTitle:text forState:UIControlStateNormal];
    
    //清空数据，退出控件
    [popCon dismissPopoverAnimated:YES];
    popCon = nil;
}

- (IBAction)dropdownBtnTapped:(UIButton *)sender {
    //创建下拉菜单
    [self createThePopViewControl:sender];
    if (sender == self.projectTypeBtn) {
        contentCon.list = self.projectTypeNames;
    }else if (sender == self.chargeDiffBtn){
        contentCon.list = self.chargeDiffKeys;
    }else if (sender == self.repairTypeBtn){
        contentCon.list = self.repairTypeNames;
    }
    //刷新下拉菜单数据
    [contentCon.myTableView reloadData];
}


@end
